import { useGlobalStore } from '@/store'

// 参数拼接
function param(url: string, data: any) {
    let param = ''
    for (let k in data) {
        let value = data[k] != null ? data[k] : ''
        param += '&' + k + '=' + encodeURIComponent(value)
    }

    url += url.indexOf('?') < 0 ? '?' : '&'
    url += param ? param.substring(1) : ''
    return url
}

function androidMethod(options: any) {
    try {
        uni.navigateTo({
            url: param('/pages/tools/CustomModal', {
                title: options.title,
                content: options.content,
                showCancel: options.showCancel,
                confirmText: options.confirmText,
                cancelText: options.cancelText,
                noBack: options.noBack
            })
        })
        // 触发一次
        uni.$once('CModelCallback', res => {
            if (options.success && typeof options.success === 'function') {
                setTimeout(() => {
                    options.success.call(null, res)
                }, 400)
            }
        })
    } catch (e) {
        if (options.fail && typeof options.fail === 'function') {
            setTimeout(() => {
                options.fail.call(null, e)
            }, 400)
        }
    } finally {
        if (options.complete && typeof options.complete === 'function') {
            setTimeout(() => {
                options.complete.call(null, {})
            }, 400)
        }
    }
}
function iosMethod(options: any) {
    let style: any = {
        buttons: ['取消', '确定']
    }

    // 如果有自定义confirmText 则修改数组的第一个元素
    if (options.confirmText) style.buttons[1] = options.confirmText
    // 如果有自定义的cancelText 则修改第二个元素
    if (options.cancelText) style.buttons[0] = options.cancelText
    // 如果不显示 取消按钮 则 取数组的第一个就行
    if (options.showCancel == false) style.buttons = style.buttons.slice(1, 1)
    // 修改标题
    if (options.title) style.title = options.title

    plus.nativeUI.confirm(
        options.content,
        ({ index }) => {
            if (index == 1 || (options.showCancel == false && index == 0)) options.success instanceof Function ? options.success.call(null, { confirm: true }) : ''
        },
        style
    )
}
export const showModal = (options: any) => {
    const globalStore = useGlobalStore()
    if (!globalStore.canIpop) {
        console.log('已有弹窗, 不继续弹窗')
        return
    }
    // #ifdef APP-PLUS
    if (uni.$u.os() == 'android') {
        androidMethod(options)
    } else {
        iosMethod(options)
    }
    // #endif

    // #ifndef APP-PLUS
    uni.showModal(options)
    // #endif
}

const install = () => {
    uni.$u.$showModal = showModal
}

export default {
    install
}
